import AMapLoader from '@amap/amap-jsapi-loader';
let AMapInstance = null;

export const amapPromise = new Promise((resolve, reject) => {
  if (AMapInstance) {
    resolve(AMapInstance);
  }
  AMapLoader.load({
    key: '17655bbe7c87ca761dc007e0c820fccb', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.AutoComplete', 'AMap.Scale'], // 需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((AMap) => {
      AMapInstance = AMap;
      resolve(AMapInstance);
    })
    .catch((err) => {
      reject(err);
    });
});
export const randomKey = () => Math.floor(Math.random() * 10000).toString();

export const amapAddressToMyAddress = (amapAddress) => {
  const reg =
    /(?<province>[^省]+省|.+自治区|[^澳门]+澳门|[^香港]+香港|[^市]+市)?(?<city>[^自治州]+自治州|[^特别行政区]+特别行政区|[^市]+市|.*?地区|.*?行政单位|.+盟|市辖区|[^县]+县)(?<county>[^县]+县|[^市]+市|[^镇]+镇|[^区]+区|[^乡]+乡|.+场|.+旗|.+海域|.+岛)?(?<address>.*)/g;
  const matchResult = reg.exec(amapAddress.district);
  console.log('xxxx: ', matchResult);
  return {
    address_name: amapAddress.name,
    province: matchResult?.groups?.province,
    city: matchResult?.groups?.city,
    district: matchResult?.groups?.county,
    subArea: amapAddress.address,
    full_address: amapAddress.district + amapAddress.address,
    location: [amapAddress.location.lng, amapAddress.location.lat].toString(),
  };
};

export const formatNumber = (num) => {
  if (isNaN(num)) return '0.00';
  const fixedNum = num.toFixed(2);
  return fixedNum.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

export const formatDatetime = (str: string) => {
  if (str?.includes('T')) {
    return str.replace(/T/, ' ').slice(0, -3);
  }
  return '';
};
